package com.office.shop.by.widget;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.util.Log;
import android.widget.RemoteViews;
import com.office.shop.by.*;
import com.office.shop.by.components.*;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import static android.graphics.BitmapFactory.decodeResource;

public class WidgetProvider extends AppWidgetProvider {

    private static final String TAG = "WidgetProvider";
    private static final String PREFS_NAME = CConfig.mainPackage+".MultiAccActivity";
    public static final SharedPreferences sharedPreferences = null;

    public static int current_acc;
    public static AppWidgetManager _appWidgetManager;
    public static Context _context;
    public static int _appWidgetId;

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        Log.d(TAG, "onUpdate");

        final Context context_t = context;
        final AppWidgetManager wm = appWidgetManager;
        final int[] ids = appWidgetIds;

        CountDownTimer timer = new CountDownTimer (CFormat.dateToMilliSeconds(1, 0, 2099, 0, 0),CConfig.widgetUpdateTime) {

                    public void onTick(long millisUntilFinished)
                    {
                       final int N = ids.length;
                            for (int i=0; i<N; i++) {
                                updateAppWidget(context_t, wm, ids[i]);
                            }
                    }
                    public void onFinish() { }

        }.start();
    }
    
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        Log.d(TAG, "onDeleted");
        final int N = appWidgetIds.length;
        for (int i=0; i<N; i++) {
            WidgetConfigure.delete(context, appWidgetIds[i]);
        }
    }

    @Override
    public void onEnabled(Context context) {
        Log.d(TAG, "onEnabled");
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(
                new ComponentName(CConfig.mainPackage, ".widget.WidgetBroadcastReceiver"),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
    }

    @Override
    public void onDisabled(Context context) {
        Log.d(TAG, "onDisabled");
        PackageManager pm = context.getPackageManager();
        pm.setComponentEnabledSetting(
                new ComponentName(CConfig.mainPackage, ".widget.WidgetBroadcastReceiver"),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
    }

    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager, int appWidgetId)
    {
          _appWidgetManager =  appWidgetManager;
          _context = context;
          _appWidgetId  = appWidgetId;
          CAccounts.init(context);
          WidgetProvider.current_acc = WidgetConfigure.load(context, appWidgetId);
          new JSONParser().execute();

    }

    private static class JSONParser extends AsyncTask<String, Void, JSONObject>
    {
        protected JSONObject doInBackground(String arg[]) {
          JSONObject output = new JSONObject();
          try
          {
            if(CAuth.login(CAccounts.logins[WidgetProvider.current_acc],CAccounts.passwords[WidgetProvider.current_acc]))
               output = CHttp.postJSON(CConfig.serverUrl, CAuth.getLogin());
            else
               output = null;
          }
          catch(Exception e)
          {
            e.printStackTrace();
          }
          return output;
        }
        protected void onPostExecute(JSONObject output) {
            try {
                      if(output!=null)
                      {
                          RemoteViews views = null;
                          int themeid = WidgetConfigure.loadTheme(_context,_appWidgetId);

                          if(themeid == 0 )
                            views = new RemoteViews(_context.getPackageName(), R.layout.widget_white);
                          else
                            views = new RemoteViews(_context.getPackageName(), R.layout.widget_black);

                          views.setTextViewText(R.id.name, output.getString("real_url"));
                          views.setTextViewText(R.id.sum, CFormat.numberFormat(output.getJSONObject("host").getString("purse_sum")));
                          if(output.getJSONObject("host").getString("status").equals("active"))
                               views.setTextViewText(R.id.status, _context.getString(R.string.WidgetServiceActive));
                            else
                                views.setTextViewText(R.id.status,_context.getString(R.string.WidgetServiceNoActive));

                          Bitmap img = CImages.fetchImage(output.getString("img_url"));
                          if(img != null)
                            views.setImageViewBitmap(R.id.img,img);
                          else
                            views.setImageViewBitmap(R.id.img, decodeResource(_context.getResources(), R.drawable.icon));

                          _appWidgetManager.updateAppWidget(_appWidgetId, views);
                      }
            } catch (JSONException e) {
                     e.printStackTrace();

            }
        }
    }
}


